#include <stdio.h>
#include <sys/types.h>//open
#include <sys/stat.h>//open
#include <fcntl.h>//open
#include <unistd.h>//close
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>//mmap
#include <linux/input.h>//strcut  input_event
#include <sys/socket.h>
#include <netinet/in.h> // for struct sockaddr_in
#include <string.h> // for memset
#include <stdlib.h>
int main(int argc, char *argv[])
{
    //创建套接字
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0) {
        perror("socket creation failed");
        return -1;
    }

    //配置IPV4协议内容
    struct sockaddr_in srvaddr;
    srvaddr.sin_family = AF_INET;//IPV4
    srvaddr.sin_port = htons(55555);//（端口号）
    //绑定服务器ubuntu12.04的IP
    srvaddr.sin_addr.s_addr = inet_addr("192.168.64.7");

    //绑定地址
    if(bind(socket_fd, (struct sockaddr *)&srvaddr, sizeof(srvaddr)) < 0) {
        perror("bind failed");
        return -1;
    }

    //监听
    if(listen(socket_fd, 4) < 0) {
        perror("listen failed");
        return -1;
    }

    printf("Waiting for client connection...\n");

    //等待客户连接
    int conn_fd = accept(socket_fd, NULL, NULL);
    if(conn_fd < 0) {
        perror("accept failed");
        return -1;
    }

    printf("连接成功\n");

    //畅聊
    long long  msg[3];

    FILE* fp=fopen("1.txt","w");
	if (fp == NULL) {
        printf("无法打开文件。\n");
    	exit(-1);
	}

while(!feof(fp))
{
    memset(msg, 0, sizeof(msg)); // 初始化数组，数组中的值全部赋值为0

    ssize_t numBytesRcvd = recv(conn_fd, msg, sizeof(msg), 0);
    if(numBytesRcvd < 0) {
        perror("recv failed");
        break;
    } else if(numBytesRcvd == 0) {
        printf("Client disconnected\n");
        break;
    }

    if(sizeof(msg) > 0) {
        printf("Received: %lld %f %f\n", msg[0],(float)msg[1],(float)msg[2]);
        fprintf(fp, "%lld %f %f\n", msg[0],(float)msg[1],(float)msg[2]);
    } else {
        printf("Received an empty message\n");
    }
}

    printf("已退出！\n");
    //挂电话
    close(socket_fd);
    close(conn_fd);   
    fclose(fp);
    return 0;
}
 